import { createRouter, createWebHistory } from 'vue-router'
import LayoutView from '../views/LayoutView.vue'
import LoginView from '../views/LoginView.vue'
import { useUserStore } from '@/stores'
import NotFoundView from '@/views/NotFoundView.vue'
import { getImportComponent } from './view'
import NProgress from './nprogress'
import type { BreadcrumbSystemType } from '@/breadcrumb'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: LayoutView,
      // redirect: { path: '/home' },
      children: [
        {
          path: '/welcome',
          name: 'welcome',
          component: getImportComponent('WelcomeView')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFoundView }
  ]
})

// 当前路由列表
const routes: string[] = []

router.beforeEach((to) => {
  NProgress.start()

  const userStore = useUserStore()
  const isLogin = !!userStore.token
  const isRootView = to.path === '/'
  const isLoginView = to.path === '/login'
  if (!isLogin) {
    if (isLoginView) {
      return true
    }
    return { name: 'login' }
  }

  /**
   * 下面都是登录之后的逻辑
   */

  // welcome 是任何用户都可以看到的页面
  if (to.name === 'welcome') {
    return true
  }

  // 需要新增的路由列表
  const addRoutes = userStore.permissionRouteNames.filter((n) => !routes.includes(n))
  if (addRoutes.length > 0) {
    addRoutes.forEach((n) => {
      const route = userStore.permissionRoutes.find((route) => route.name === n)
      if (route) {
        if (route?.meta?.full) {
          router.addRoute(route)
        } else {
          router.addRoute('layout', route)
        }
        routes.push(n)
      }
    })
  }
  // 需要删除的路由列表
  const delRoutes = routes.filter((n) => !userStore.permissionRouteNames.includes(n))
  if (delRoutes.length > 0) {
    delRoutes.forEach((n) => {
      router.removeRoute(n)
      routes.splice(routes.indexOf(n), 1)
    })
  }

  // 由于不匹配路由，to.path 是稳定的，所以这里需要根据权限路由寻找一遍
  const notMatchRoute = userStore.permissionRoutes.find((route) => route.path === to.path)
  if (isRootView || isLoginView) {
    if (routes.length === 0) {
      // 目前是登录了的，所以找不到匹配的路由，显示 welcome 欢迎页面
      // 说明当前用户所有权限都为空，只显示欢迎界面
      return { name: 'welcome' }
    }
    return { name: routes[0] }
  } else if (notMatchRoute && addRoutes.includes(notMatchRoute.name as string)) {
    // 这里必须使用 path，因为这里才动态添加或者删除路由，可能已经匹配到 NotFound 路由了，只要 path 是正确的(也就是已经添加到动态路由中)，重新跳转下就可以了
    // 首次刷新浏览器会出现 [Vue Router warn]: No match found for location with path "/common-system/home" 警告，可以不用管它
    return { path: to.path, replace: true }
  } else if (notMatchRoute && routes.includes(notMatchRoute.name as string)) {
    // true 允许本次路由导航
    return true
  }
  // false 取消当前的导航
  // return false
  // 都没有匹配，返回根
  // return { name: 'not-found' }
  return { path: '/' }
})

router.afterEach((to) => {
  const { visible, full } = to.meta
  // 只允许动态路由注册tab，visible = true, full = true 恰好是动态加载路由都具有属性
  if (visible && !full) {
    const userStore = useUserStore()
    const title = to.meta?.title || ''
    const icon = to.meta?.icon || ''
    userStore.tabToggle({
      title: title as string,
      icon: icon as BusinessIconType,
      path: to.path
    })
    if (to.meta?.menu) {
      userStore.menu = to.path
    }
    if (to.meta?.breadcrumbs) {
      userStore.breadcrumbs = to.meta.breadcrumbs as string[]
      const system = userStore.permissionSystemNames.find((s) => to.path.indexOf(s) === 0)
      if (system) {
        userStore.system = system as BreadcrumbSystemType
      }
    }
  }
  NProgress.done()
})

router.onError(() => NProgress.done())

export default router
